/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.dc.task;

import akka.actor.ActorRef;
import com.cxhd.dc.DataCache;
import com.cxhd.dc.DataConfig;
import com.cxhd.dc.actor.ActorManager;
import com.cxhd.dc.tool.FileUtil;
import com.cxhd.dc.tool.HttpClientUt;
import com.cxhd.dc.tool.Tools;
import com.cxhd.dc.tool.ZipFileTool;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 *
 * @author Administrator
 */
public class SendPacsQueue implements Runnable {

    private boolean start = true;
    private BlockingQueue sendPacsQueue;
    ActorManager actorManager = ActorManager.getIntance();
    private DataCache dataCache;

    private static final org.apache.log4j.Logger logger1 = org.apache.log4j.Logger.getLogger("FileToZip");

    public SendPacsQueue(BlockingQueue sendPacsQueue) {
        this.sendPacsQueue = sendPacsQueue;
        dataCache = DataCache.getInstance();
    }

    @Override
    public void run() {
        while (true) {
            try {
                String filepath = (String) sendPacsQueue.take();
                String device = filepath.split("@")[1];
                String reaPath = filepath.split("@")[0];
                File sendFile = new File(reaPath);
                String mode = DataConfig.getInstance().getRecFileMode();
                //判断执行哪一种模式
                if (mode.equalsIgnoreCase("0")) {
                    sendPacs(device, reaPath, sendFile);
                } else if (mode.equalsIgnoreCase("1")) {
                    saveGcache(sendFile.listFiles(), true);
                } else if (mode.equalsIgnoreCase("2")) {
                    saveGcache(sendFile.listFiles(), false);
                    sendPacs(device, reaPath, sendFile);
                }

            } catch (Exception e) {
            }
        }
    }

    public void saveGcache(File[] files, boolean delete) {
        if (files != null) {

            try {
                String basePath = "g:/gcache/rispacs.net/";

                for (File f : files) {
                    String patientId = FileUtil.getOldPatientId(f.getAbsolutePath());
                    File file = new File(basePath + patientId);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    file = new File(basePath + patientId + "/" + f.getName());
                    if (!delete) {
                        Files.copy(f, file);
                    } else {
                        Files.move(f, file);
                    }

                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    public void sendPacs(String device, String reaPath, File sendFile) {

        try {
            Runtime r = Runtime.getRuntime();
            boolean flag = false;
            Process p = r.exec("cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + DataConfig.getInstance().getAET() + "@" + DataConfig.getInstance().getAe_ip() + ":" + DataConfig.getInstance().getAe_port() + " " + reaPath + "   -set 00100021= \"Atlas\" -set 00080005= \"GB18030\" -set 00080080=\"" + FileUtil.getSNtoHospitalName(device) + "\" -set 00080090=\"" + device + "\"");
            //logger.info("cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + this.pacsInfo[2] + "@" + this.pacsInfo[0] + ":" + this.pacsInfo[1] + " " + newFloder.getAbsolutePath() + " -set 00080005= \"GB18030\" -set 00080080=\"" + ApProperties.getSNtoHospitalName(device) + "\"");
            System.out.println("cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + DataConfig.getInstance().getAET() + "@" + DataConfig.getInstance().getAe_ip() + ":" + DataConfig.getInstance().getAe_port() + " " + reaPath + "   -set 00100021= \"Atlas\" -set 00080005= \"GB18030\" -set 00080080=\"" + FileUtil.getSNtoHospitalName(device) + "\" -set 00080090=\"" + device + "\"");
            //writeText("c:/dcmsyst/send.txt", "cmd.exe /c C:\\dcmsyst\\tool-2.0.26\\bin\\dcmsnd -device " + device + " " + this.pacsInfo[2] + "@" + this.pacsInfo[0] + ":" + this.pacsInfo[1] + " " + newFloder.getAbsolutePath());

            new Thread(new cmdResult(p.getInputStream(), "success", null, null)).start();
            new Thread(new cmdResult(p.getErrorStream(), "error", device, sendFile)).start();
//            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
//            String msg = null;
//            while ((msg = br.readLine()) != null) {
//                // logger1.info(msg);
//                // System.out.println("info msg : " + msg);
//            }
//            BufferedReader er = new BufferedReader(new InputStreamReader(p.getErrorStream()));
//            String error = null;
//            while ((error = er.readLine()) != null) {
//                logger1.error(error);
//                flag = true;
//
//            }
            //p.waitFor();
            //p.destroy();

//            if (!flag) {
//                if (DataConfig.getInstance().getCacheServer() != null) {
//                    actorManager.getActor("SendCacheServerActor").tell(device + "@" + sendFile.getAbsolutePath(), ActorRef.noSender());
//                } else {
//                    for (File del : sendFile.listFiles()) {
//                        //System.out.println("K:/dicomTest/" + del.getName());
//
//                        del.delete();
//                    }
//                }
//                sendFile.delete();
//
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class cmdResult implements Runnable {

        private InputStream ins;
        private String type;
        private boolean flag = true;
        private String device;
        private File sendFile;

        public cmdResult(InputStream ins, String type, String device, File sendFile) {
            this.ins = ins;
            this.type = type;
            this.device = device;
            this.sendFile = sendFile;
        }

        @Override
        public void run() {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    if (type.equalsIgnoreCase("error")) {
                        System.out.println(type + ":" + line);
                    }
                    flag = false;
                }
                if (type.equalsIgnoreCase("error")) {
                    if (flag) {
                        if (DataConfig.getInstance().getCacheServer() != null) {
                            actorManager.getActor("SendCacheServerActor").tell(device + "@" + sendFile.getAbsolutePath(), ActorRef.noSender());
                        } else {
                            for (File del : sendFile.listFiles()) {
                                //System.out.println("K:/dicomTest/" + del.getName());

                                del.delete();
                            }
                        }
                        sendFile.delete();
                        System.out.println("文件已经删除");

                    } else {
                        sendsms(device);
                        System.out.println("发送短信预警");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void sendsms(String device) {
            String content = device + "(" + FileUtil.getSNtoHospitalName(device) + ")";
            String url = "http://183.232.150.37/SmsServer/smsForDICOM.jsp";
            System.out.println("发送短信");
            if (DataConfig.getInstance().getNoticeNo() != null) {
                
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("phone", DataConfig.getInstance().getNoticeNo()));
                params.add(new BasicNameValuePair("content", content));
                HttpClientUt.httpPost(url, params);
                 System.out.println("发送短信成功"+DataConfig.getInstance().getNoticeNo());
            }

        }

    }

}
